import React, { useState } from 'react';
import { View, Text, StyleSheet, ScrollView, Switch, TouchableOpacity, Modal, Alert } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import usePlanStore from '../store/planStore';
import { useTheme } from '../hooks/useTheme';
import { THEME_MODE } from '../utils/constants';
import { createCommonStyles } from '../styles/commonStyles';
import Button from '../components/common/Button';

const SettingsScreen = () => {
  const { settings, updateSettings, clearAllData, loadAllData } = usePlanStore();
  const { theme } = useTheme();
  const dynamicStyles = createCommonStyles(theme);
  const [showClearConfirm, setShowClearConfirm] = useState(false);
  const [isClearing, setIsClearing] = useState(false);

  const handleClearData = async () => {
    setIsClearing(true);
    // 先关闭确认对话框
    setShowClearConfirm(false);
    
    try {
      const result = await clearAllData();
      if (result.success) {
        // 重新加载数据（此时应该是空的）
        await loadAllData();
        // 显示成功提示
        Alert.alert('成功', '所有数据已清理');
      } else {
        Alert.alert('错误', result.error || '清理数据失败');
      }
    } catch (error) {
      Alert.alert('错误', error.message || '清理数据时发生错误');
    } finally {
      setIsClearing(false);
    }
  };

  return (
    <SafeAreaView style={[dynamicStyles.container, { backgroundColor: theme.colors.background }]} edges={['top']}>
      <ScrollView style={[dynamicStyles.content, { backgroundColor: theme.colors.background }]}>
        <View style={[dynamicStyles.card, { backgroundColor: theme.colors.card }]}>
          <View style={styles.settingItem}>
            <View style={styles.settingLabelContainer}>
              <Text style={[styles.settingLabel, { color: theme.colors.text }]}>自动迁移未完成计划</Text>
              <Text style={[styles.settingHint, { color: theme.colors.textSecondary }]}>
                将今日未完成的计划自动推到明天（周末不迁移）
              </Text>
            </View>
            <Switch
              value={settings.autoMigrate}
              onValueChange={(value) => updateSettings({ autoMigrate: value })}
            />
          </View>
        </View>

        <View style={[dynamicStyles.card, { backgroundColor: theme.colors.card }]}>
          <View style={styles.settingItem}>
            <Text style={[styles.settingLabel, { color: theme.colors.text }]}>启用通知提醒</Text>
            <Switch
              value={settings.enableNotifications}
              onValueChange={(value) =>
                updateSettings({ enableNotifications: value })
              }
            />
          </View>
        </View>

        <View style={[dynamicStyles.card, { backgroundColor: theme.colors.card }]}>
          <Text style={[styles.sectionTitle, { color: theme.colors.text }]}>主题设置</Text>
          
          <TouchableOpacity
            style={[
              styles.themeOption,
              settings.theme === THEME_MODE.LIGHT && styles.themeOptionActive,
              { borderColor: theme.colors.border }
            ]}
            onPress={() => updateSettings({ theme: THEME_MODE.LIGHT })}
          >
            <View style={styles.themeOptionContent}>
              <View style={[styles.themePreview, { backgroundColor: '#FFFFFF' }]} />
              <Text style={[styles.themeOptionLabel, { color: theme.colors.text }]}>
                浅色模式
              </Text>
            </View>
            {settings.theme === THEME_MODE.LIGHT && (
              <Text style={[styles.checkmark, { color: theme.colors.primary }]}>✓</Text>
            )}
          </TouchableOpacity>

          <TouchableOpacity
            style={[
              styles.themeOption,
              settings.theme === THEME_MODE.DARK && styles.themeOptionActive,
              { borderColor: theme.colors.border }
            ]}
            onPress={() => updateSettings({ theme: THEME_MODE.DARK })}
          >
            <View style={styles.themeOptionContent}>
              <View style={[styles.themePreview, { backgroundColor: '#000000' }]} />
              <Text style={[styles.themeOptionLabel, { color: theme.colors.text }]}>
                深色模式
              </Text>
            </View>
            {settings.theme === THEME_MODE.DARK && (
              <Text style={[styles.checkmark, { color: theme.colors.primary }]}>✓</Text>
            )}
          </TouchableOpacity>

          <TouchableOpacity
            style={[
              styles.themeOption,
              (settings.theme === THEME_MODE.AUTO || settings.theme === THEME_MODE.TIME) && styles.themeOptionActive,
              { borderColor: theme.colors.border }
            ]}
            onPress={() => updateSettings({ theme: THEME_MODE.AUTO })}
          >
            <View style={styles.themeOptionContent}>
              <View style={[styles.themePreview, styles.themePreviewAuto]} />
              <View style={styles.themeOptionTextContainer}>
                <Text style={[styles.themeOptionLabel, { color: theme.colors.text }]}>
                  跟随系统
                </Text>
                <Text style={[styles.themeOptionHint, { color: theme.colors.textSecondary }]}>
                  跟随系统主题设置（包括时间自动切换）
                </Text>
              </View>
            </View>
            {(settings.theme === THEME_MODE.AUTO || settings.theme === THEME_MODE.TIME) && (
              <Text style={[styles.checkmark, { color: theme.colors.primary }]}>✓</Text>
            )}
          </TouchableOpacity>
        </View>

        {/* 清理缓存 */}
        <View style={[dynamicStyles.card, { backgroundColor: theme.colors.card }]}>
          <Text style={[styles.sectionTitle, { color: theme.colors.text }]}>数据管理</Text>
          <TouchableOpacity
            style={[
              styles.clearButton,
              { backgroundColor: theme.colors.error + '20', borderColor: theme.colors.error }
            ]}
            onPress={() => setShowClearConfirm(true)}
            activeOpacity={0.7}
          >
            <Text style={[styles.clearButtonText, { color: theme.colors.error }]}>
              清理所有数据
            </Text>
          </TouchableOpacity>
          <Text style={[styles.clearHint, { color: theme.colors.textSecondary }]}>
            此操作将删除所有计划数据，无法恢复。每年1月1日会自动执行。
          </Text>
        </View>

        <View style={styles.infoSection}>
          <Text style={[styles.infoText, { color: theme.colors.textSecondary }]}>PlanFlow - 个人计划管理</Text>
        </View>
      </ScrollView>

      {/* 清理确认对话框 */}
      <Modal
        visible={showClearConfirm}
        transparent={true}
        animationType="fade"
        onRequestClose={() => setShowClearConfirm(false)}
      >
        <View style={[styles.modalOverlay, { backgroundColor: 'rgba(0, 0, 0, 0.5)' }]}>
          <View style={[styles.modalContent, { backgroundColor: theme.colors.card }]}>
            <Text style={[styles.modalTitle, { color: theme.colors.text }]}>确认清理数据</Text>
            <Text style={[styles.modalMessage, { color: theme.colors.textSecondary }]}>
              此操作将永久删除所有计划数据（包括日计划、周计划、月计划），此操作无法撤销。
            </Text>
            <Text style={[styles.modalWarning, { color: theme.colors.error }]}>
              确定要继续吗？
            </Text>
            
            <View style={styles.modalButtons}>
              <Button
                title="取消"
                variant="secondary"
                onPress={() => setShowClearConfirm(false)}
                style={styles.modalButton}
              />
              <Button
                title={isClearing ? "清理中..." : "确认清理"}
                onPress={handleClearData}
                style={styles.modalButton}
                disabled={isClearing}
              />
            </View>
          </View>
        </View>
      </Modal>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  settingItem: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  settingLabelContainer: {
    flex: 1,
    marginRight: 12,
  },
  settingLabel: {
    fontSize: 16,
    marginBottom: 4,
  },
  settingHint: {
    fontSize: 12,
    lineHeight: 16,
  },
  sectionTitle: {
    fontSize: 18,
    fontWeight: '600',
    marginBottom: 12,
  },
  themeOption: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: 12,
    marginBottom: 8,
    borderRadius: 8,
    borderWidth: 2,
  },
  themeOptionActive: {
    borderWidth: 2,
  },
  themeOptionContent: {
    flexDirection: 'row',
    alignItems: 'center',
    flex: 1,
  },
  themePreview: {
    width: 24,
    height: 24,
    borderRadius: 12,
    marginRight: 12,
    borderWidth: 1,
    borderColor: '#C6C6C8',
  },
  themePreviewAuto: {
    backgroundColor: '#F2F2F7',
    borderColor: '#000',
    borderWidth: 1,
  },
  themeOptionTextContainer: {
    flex: 1,
  },
  themeOptionLabel: {
    fontSize: 16,
    marginBottom: 2,
  },
  themeOptionHint: {
    fontSize: 12,
  },
  checkmark: {
    fontSize: 20,
    fontWeight: 'bold',
    marginLeft: 8,
  },
  clearButton: {
    paddingVertical: 12,
    paddingHorizontal: 16,
    borderRadius: 8,
    borderWidth: 1,
    alignItems: 'center',
    marginTop: 8,
  },
  clearButtonText: {
    fontSize: 16,
    fontWeight: '600',
  },
  clearHint: {
    fontSize: 12,
    marginTop: 8,
    lineHeight: 16,
  },
  modalOverlay: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 20,
  },
  modalContent: {
    borderRadius: 16,
    padding: 24,
    width: '100%',
    maxWidth: 400,
  },
  modalTitle: {
    fontSize: 20,
    fontWeight: 'bold',
    marginBottom: 16,
  },
  modalMessage: {
    fontSize: 14,
    lineHeight: 20,
    marginBottom: 12,
  },
  modalWarning: {
    fontSize: 14,
    fontWeight: '600',
    marginBottom: 24,
  },
  modalButtons: {
    flexDirection: 'row',
    gap: 12,
  },
  modalButton: {
    flex: 1,
  },
  infoSection: {
    marginTop: 32,
    alignItems: 'center',
  },
  infoText: {
    fontSize: 14,
    marginBottom: 4,
  },
});

export default SettingsScreen;

